﻿/*
创建人：zhangrj
日期：2023-07-28
描述：转工计划排产确认接收js
*/
var page = {
    pageTotal: 0,
    pageSize: 20,
    pageNumber: 1,
    rootPath: getRootPath(), //网站根路径
    url: getRootPath() + "/Ashx/ApsHandler/ApsPlanConfirmHandler.ashx",
    //初始化页面
    init: function () {
        page.bind();
        dialogPage.bind();
        page.initPage();
        customizedEasyuiPagination('pp'); //定制化分页
    },
    //页面事件绑定
    bind: function () {
        //排产列表加载
        $("#gdApsPlanInfo").datagrid({
            onLoadSuccess: function (data) {
                $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                    total: page.pageTotal,
                    pageSize: page.pageSize,
                    pageNumber: page.pageNumber
                });
                customizedEasyuiPagination('pp'); //定制化分页
            },
            onDblClickRow: function (rowIndex, rowData) {
                dialogPage.init(rowData);
            },
            onClickRow: function (rowIndex, rowData) {
                $(this).datagrid('acceptChanges')
            },
            columns: [[
                 { field: 'ck', title: '选择', checkbox: true },
                 { field: 'MFGORDERNAME', title: '订单号', width: 150 },
                 { field: 'CONTAINERNAME', title: '批次号', width: 150 },
                 { field: 'PRODUCTDESCRIPTION', title: '零件名称', width: 150 },
                 { field: 'WORKFLOWINFO', title: '工艺版次', width: 150 },
                 { field: 'NOWWORKFLOWSTEPNAME', title: '当前序', width: 120 },
                 { field: 'WORKFLOWSTEPNAME', title: '转工序', width: 120 },
                 { field: 'APSQTY', title: '计划数', width: 60 },
                 { field: 'MAINFACTORYNAME', title: '主制工厂', width: 120 },
                 { field: 'ASSISFACTORYNAME', title: '承制工厂', width: 120 },
                 { field: 'CONTAINERTYPENAME', title: '批次类型', width: 100 },
                 { field: 'APSTYPENAME', title: '排产策略', width: 80 },
                 { field: 'CREATEDATE', title: '计划生成时间', width: 100,
                     formatter: function (value, row, index) {
                         if (!isNullOrWhiteSpaceStr(value)) {
                             return dayjs(value).format('YYYY-MM-DD');
                         }
                     }
                 },
                 { field: 'STARTTIME', title: '计划开始时间', width: 150,
                     formatter: function (value, row, index) {
                         if (!isNullOrWhiteSpaceStr(value)) {
                             return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
                         }
                     }
                 },
                 { field: 'ENDTIME', title: '计划结束时间', width: 150,
                     formatter: function (value, row, index) {
                         if (!isNullOrWhiteSpaceStr(value)) {
                             return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
                         }
                     }
                 },
                 { field: 'CONFIRMEMP', title: '转出人', width: 100 },
                 { field: 'CONFIRMDATE', title: '转出时间', width: 150,
                     formatter: function (value, row, index) {
                         if (!isNullOrWhiteSpaceStr(value)) {
                             return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
                         }
                     }
                 },
                 { field: 'SHIPRECPLANSTARTDATE', title: '反馈开始时间', width: 150, editor: 'datetimebox' },
                 { field: 'SHIPRECPLANENDDATE', title: '反馈结束时间', width: 150, editor: 'datetimebox' },
                 { field: 'RECEIVEEMP', title: '接收人', width: 100 },
                 { field: 'SHIPRECEIVEDATE', title: '接收时间', width: 150,
                     formatter: function (value, row, index) {
                         if (!isNullOrWhiteSpaceStr(value)) {
                             return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
                         }
                     }
                 },
                 { field: 'STATUSNAME', title: '确认状态', width: 60 }
                ]]
        });
        //查询按钮
        $('#btnSearch').on("click", function () {
            page.clearPage(false, true, true);
            page.pageNumber = 1;
            page.searchData();
        });
        //分页事件
        $('#pp').pagination({
            onSelectPage: function (pageNumber, pageSize) {
                page.clearPage(false, true, true);
                customizedEasyuiPagination('pp'); //定制化分页
                page.pageSize = pageSize; page.pageNumber = pageNumber;
                page.searchData();
            }
        });
        //绑定分页go按钮
        $('#pageGo').on("click", function () {
            page.clearPage(false, true, true);
            var pageNumber = $(this).parents('tr').find('.pagination-num').val();
            page.pageNumber = pageNumber;
            page.searchData();
        });
        //清除按钮
        $('#btnReset').on("click", function () {
            page.clearPage(true, true, true);
            page.pageNumber = 1; page.pageTotal = 0
            $('#pp').pagination('refresh', {
                total: page.pageTotal,
                pageSize: page.pageSize,
                pageNumber: page.pageNumber
            });
        });
        //状态下拉选择
        $('#selStatus').combobox({
            onSelect: function (record) {
                if (record.value === "2") {//已确认
                    clearEasyuiDataGrid("gdApsPlanInfo");
                    $("#btnReceive").show();
                    $("#btnCancel").hide();
                } else {
                    clearEasyuiDataGrid("gdApsPlanInfo");
                    $("#btnReceive").hide();
                    $("#btnCancel").show();
                }
            }
        });
        //扫描批次事件
        $('#txtScanContainer').textbox({
            onChange: function (n, o) {
                page.pageNumber = 1;
                page.searchData();
            }
        });
        //扫描批次事件
        $('#txtScanOrder').textbox({
            onChange: function (n, o) {
                page.pageNumber = 1;
                page.searchData();
            }
        });
        //计划接收
        $('#btnReceive').on("click", function () {
            page.clearPage(false, false, true);
            page.saveReceive();
        });
        //撤销接收
        $('#btnCancel').on("click", function () {
            page.clearPage(false, false, true);
            page.cancelReceive();
        });
        //导出 add by lb 2024-07-31
        $('#btnExport').on("click", function () {
            page.clearPage(false, false, true);
            page.exportReceive();
        });
    },
    //初始化页面
    initPage: function () {
        page.post(page.url, { action: "InitPageData" }, true, function (res) {
            if (!res.Result) {
                displayMessage(res.Message, res.Result);
                return;
            }
            $("#selMainFactory").combobox({//主制分厂
                valueField: 'FACTORYID',
                textField: 'FACTORYNAME',
                panelHeight: 200,
                data: res.DBDataSet.dtMainFactory //下拉数据
            });
        });
    },
    //查询
    searchData: function () {
        var params = {
            PageSize: page.pageSize,
            PageIndex: page.pageNumber
        };
        var datas = $("#queryForm").serializeArray();
        $.each(datas, function () {
            params[this.name] = this.value;
        });
        var formData = {
            action: "GetApsPlanShipReceiveDatasByPage",
            params: JSON.stringify(params)
        };
        page.post(page.url, formData, true, function (res) {
            if (!res.Result) {
                displayMessage(res.Message, res.Result);
                return;
            }
            page.pageTotal = res.RowCount;
            $("#gdApsPlanInfo").datagrid('loadData', { total: res.RowCount, rows: res.DBTable });
        });
    },
    //确认接收
    saveReceive: function () {
        $("#btnReceive").linkbutton('disable');
        var selected = $("#gdApsPlanInfo").datagrid("getChecked");
        if (selected.length === 0) {
            displayMessage2("请选择数据", false, ["btnReceive"]);
            return;
        }
        var result = true;
        $.each(selected, function (i) {
            if (!isNullOrWhiteSpaceStr(selected[i].SHIPRECPLANSTARTDATE) || !isNullOrWhiteSpaceStr(selected[i].SHIPRECPLANENDDATE)) {
                result = false;
            }
        });
        if (!result) {
            displayMessage2("存在反馈日期，需主制分厂确认", false, ["btnReceive"]);
            return;
        }
        $.messager.confirm('确认', "是否确认接收？", function (r) {
            if (r) {
                var formData = {
                    action: "SaveApsPlanShipReceiveDatas",
                    type: 1,
                    params: JSON.stringify(selected)
                };
                page.post(page.url, formData, true, function (res) {
                    if (res.Result) {
                        page.searchData();
                    }
                    displayMessage2(res.Message, res.Result, ["btnReceive"]);
                });
            }
        });
    },
    //撤销接收
    cancelReceive: function () {
        $("#btnCancel").linkbutton('disable');
        var selected = $("#gdApsPlanInfo").datagrid("getChecked");
        if (selected.length === 0) {
            displayMessage2("请选择数据", false, ["btnCancel"]);
            return;
        }
        $.messager.confirm('确认', "是否撤销接收？", function (r) {
            if (r) {
                var formData = {
                    action: "CancelApsPlanShipReceiveDatas",
                    params: JSON.stringify(selected)
                };
                page.post(page.url, formData, true, function (res) {
                    if (res.Result) {
                        page.searchData();
                    }
                    displayMessage2(res.Message, res.Result, ["btnCancel"]);
                });
            }
        });
    },
    //导出接收 add by lb 2024-07-31
    exportReceive: function () {
        var params = {};
        var datas = $("#queryForm").serializeArray();
        $.each(datas, function () {
            params[this.name] = this.value;
        });
        //        var formData = {
        //            action: "exportReceive",
        //            params: JSON.stringify(params)
        //        };
       page.excuteExport("exportReceive", params);

    },
    //执行导出
    excuteExport: function (action, data) {
        $.messager.progress({ text: '', msg: '处理中...' });

        var xhr = new XMLHttpRequest();
        //设置响应类型为blob类型
        xhr.responseType = "blob";
        xhr.open("post", page.url, true); //+ "?action=apsLmCalculateExport&containers=" + JSON.stringify(containers)

        /* post 此种传参无效
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send(JSON.stringify(postData));
        */
        // post 这种传参有效
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.send("action=" + action + "&params=" + JSON.stringify(data));


        xhr.onreadystatechange = function () {
            $.messager.progress('close');
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    if (xhr.getResponseHeader("fileDownload") == "1") {
                        var a = window.document.createElement('a');
                        a.href = window.URL.createObjectURL(new Blob([this.response]));
                        a.download = decodeURI(xhr.getResponseHeader("content-disposition").split('filename=')[1]);
                        document.body.appendChild(a)
                        a.click();
                        document.body.removeChild(a)
                    } else {
                        var reader = new FileReader();
                        reader.readAsText(this.response, 'utf-8');
                        reader.onload = function (e) {
                            if (reader.result == "") { return; }
                            var result = JSON.parse(reader.result);
                            displayMessage(result.Message, false);
                        }
                    }

                }
            }
        };
        return;
    },

    //禁用按钮
    disableBtn: function () {
        $("#mainDiv").find(".easyui-linkbutton").each(function () {
            $(this).linkbutton('disable');
        });
    },
    //启用按钮
    enableBtn: function () {
        $("#mainDiv").find(".easyui-linkbutton").each(function () {
            $(this).linkbutton('enable');
        });
    },
    //清除页面（查询区域，列表区域，填写区域，是否清空消息）
    clearPage: function (query, list, msg) {
        if (query) {
            $("#queryForm").find(".easyui-textbox").each(function () {
                $(this).textbox("clear");
            });
            $("#queryForm").find(".easyui-datebox").each(function () {
                $(this).datebox("clear");
            });
            $("#selMainFactory").combobox("clear"); //主制分厂
            $("#selStatus").combobox("setValue", "2"); //确认状态
            $("#selApsType").combobox("setValue", "");
        }
        if (list) {
            clearEasyuiDataGrid("gdApsPlanInfo"); //清空列表
        }
        if (msg) {
            clearMessage();
        }
    },
    //post数据（路径，参数，是否异步，成功返回方法）
    post: function (url, param, async, callback) {
        $.ajax({
            type: "Post",
            url: url,
            data: param,
            cashe: false,
            async: async,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                callback(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                displayMessage(XMLHttpRequest.responseText, false);
                $("body").find(".easyui-linkbutton").each(function () {
                    $(this).linkbutton('enable');
                });
            }
        });
    }
};
/*---------弹窗页面对象-------------*/
var dialogPage = {
    apsPlanDetailID: "", //排产明细ID
    init: function (rowData) {
        if (rowData.STATUS !== "2") {
            return;
        }
        $("#dg").dialog({
            onClose: function () { //弹窗关闭事件
                page.enableBtn();
            }
        });
        page.disableBtn();
        dialogPage.initData(rowData);
    },
    //
    bind: function () {
        //保存反馈日期
        $('#btnSaveFeedback').on("click", function () {
            dialogPage.saveFeedDate();
        });
        //关闭弹窗
        $('#btnClose').on("click", function () {
            $("#dg").dialog("close");
        });
    },
    //初始化页面数据
    initData: function (rowData) {
        dialogPage.clearPage();
        if (rowData !== undefined) {
            dialogPage.apsPlanDetailID = rowData.APSPLANDETAILID;
            $("#shipPlanStartDate").datetimebox("setValue", rowData.SHIPRECPLANSTARTDATE);
            $("#shipPlanEndDate").datetimebox("setValue", rowData.SHIPRECPLANENDDATE);
        }
    },
    //保存转工反馈日期
    saveFeedDate: function () {
        dialogPage.disableBtn();
        var formData = {
            action: "SaveApsPlanShipFeedDatas",
            apsPlanDetailID: dialogPage.apsPlanDetailID,
            shipPlanStartDate: $("#shipPlanStartDate").datebox("getValue"),
            shipPlanEndDate: $("#shipPlanEndDate").datebox("getValue")
        };
        page.post(page.url, formData, true, function (res) {
            if (res.Result) {
                $("#dg").dialog("close");
                page.searchData();
            }
            dialogPage.enableBtn();
            displayMessage(res.Message, res.Result);
        });
    },
    //清除页面数据
    clearPage: function () {
        dialogPage.apsPlanDetailID = "";
        dialogPage.param = {};
        $("#shipPlanStartDate").datebox("clear");
        $("#shipPlanEndDate").datebox("clear");
    },
    //禁用按钮
    disableBtn: function () {
        $("#dg").find(".easyui-linkbutton").each(function () {
            $(this).linkbutton('disable');
        });
    },
    //启用按钮
    enableBtn: function () {
        $("#dg").find(".easyui-linkbutton").each(function () {
            $(this).linkbutton('enable');
        });
    }
};
$(function () {
    page.init();
});